﻿using UnityEngine;
using System.Collections;

public class ControlPlayerScript : MonoBehaviour {

	public int playerIndex = 1;
	public float movementForceMagnitude = 1.0f;
	public float bumpCooldown = 1.0f;
	public float bumpCooldownLeft = 0.0f;
	public int poisonsLeft = 1;
	public cakeScript cake;

	bool createBump = false;
	bool poisonCake = false;
	//float maxSpeed = 10.0f;

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {

		if (bumpCooldownLeft > 0.0f) 
		{
			bumpCooldownLeft -= Time.deltaTime;
		}
		else
		{
			if ( Input.GetButtonDown ("Bump" + playerIndex) )
			{
				createBump = true;
				bumpCooldownLeft = bumpCooldown;
			}
				
		}

		if (Input.GetButtonDown ("Poison" + playerIndex) && poisonsLeft > 0) 
		{
			poisonsLeft--;
			poisonCake = true;
		}




	}

	void FixedUpdate () {
		float horAxis = Input.GetAxisRaw("Horizontal" + playerIndex);
		float verAxis = Input.GetAxisRaw("Vertical" + playerIndex);





		Vector3 movementInput = new Vector3 (horAxis, 0, verAxis);
		//Debug.Log (playerIndex + ": " + movementInput);

		if (movementInput.magnitude > 1)
			movementInput.Normalize ();


		rigidbody.AddForce (movementInput * movementForceMagnitude);
		

		if(createBump)
		{
			createBump = false;
			GameObject instance = Instantiate(Resources.Load("Bump", typeof(GameObject))) as GameObject;
			instance.transform.parent = this.transform;
			instance.transform.localPosition = Vector3.zero + Vector3.forward * 0.01f;

			PushOut po = instance.GetComponent<PushOut>();
			if( po )
			{
				po.AddIgnoreCollider(this.collider);
			}
		}

		if (poisonCake) 
		{
			poisonCake = false;
			cake.PoisonCake(transform.position);

		}
	}
}
